//
//  NSDictionary+Cool.m
//  CoolFramework
//
//  Created by Felix on 13-3-29.
//  Copyright (c) 2013年 Xue Fei. All rights reserved.
//

#import "NSDictionary+Cool.h"

@implementation NSDictionary (Cool)

- (id)objectForKey:(id)aKey matchClass:(Class)aClass defaultValue:(id)defaultValue {
    id obj = self[aKey];
    if ([obj isKindOfClass:aClass]) {
        return obj;
    } else {
        return defaultValue;
    }
}

- (id)objectForKey:(id)aKey useDescription:(BOOL)useDescription defaultValue:(id)defaultValue {
    id obj = self[aKey];
    if ([obj isKindOfClass:[NSNull class]]) {
        return nil;
    }
    if (useDescription) {
        obj = [obj description];
        NSString *objNst = obj;
        if (objNst.length > 0) {
            return objNst;
        }else{
            return nil;
        }
        
    }
    
    if (obj) {
        return obj;
    } else {
        return defaultValue;
    }
}

- (id)objectForKey:(id)aKey defaultValue:(id)defaultValue
{
    id obj = self[aKey];
    if ([obj isKindOfClass:[NSNull class]]) {
        return defaultValue;
    } else if (!obj){
        return defaultValue;
    } else {
        return [obj description];
    }
}

- (NSString *)convertToJsonData
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;

    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

@end
